package cc.yihy.web.shiro.realm;

import cc.yihy.web.shiro.authc.BUsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:MxUserRealm.java
 * @Description: 企业用户登录验证模块
 * @Author: yihy
 * @Since: 2016-8-4
 * @Version: 1.0
 */
public class BUserRealm extends DefAuthorizingRealm {

    private final Logger log = LoggerFactory.getLogger(this.getClass());


    // 设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("BUserRealm");
    }


    @Override
    public Class getAuthenticationTokenClass() {
        return BUsernamePasswordToken.class;
    }

    // realm的认证方法，从数据库查询用户信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {


        String userCode = (String) token.getPrincipal();


        // 如果查询到返回认证信息AuthenticationInfo
        // 将user设置simpleAuthenticationInfo
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                "用户信息", "用户密码".toCharArray(), getName());


        return simpleAuthenticationInfo;
    }

    // 用于授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {

        // 从 principals获取主身份信息
        // 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），


        Object primaryPrincipal = principals.getPrimaryPrincipal();


        // //根据身份信息获取权限信息

        List<String> roles = new ArrayList<String>();


        List<String> permissions = new ArrayList<String>();


        // 查到权限数据，返回授权信息(要包括 上边的permissions)
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 将上边查询到授权信息填充到simpleAuthorizationInfo对象中
        simpleAuthorizationInfo.addStringPermissions(permissions);

        // 放入角色信息
        simpleAuthorizationInfo.addRoles(roles);
        return simpleAuthorizationInfo;
    }


}
